package com.cloud.wms.ui.group.presenter;


import android.text.TextUtils;

import com.cloud.core.base.BaseRxPresenter;
import com.cloud.core.http.error.ApiException;
import com.cloud.core.utils.MessageCreator;
import com.cloud.core.utils.TimeUtils;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.entity.Page;
import com.cloud.wms.http.Params;
import com.cloud.wms.http.observer.LoadingObserver;
import com.cloud.wms.http.observer.ResponseWrapper;
import com.cloud.wms.tools.PageHelper;
import com.cloud.wms.tools.RxUtils;
import com.cloud.wms.tools.TaskHelper;
import com.cloud.wms.ui.group.contract.GroupCollectContract;
import com.cloud.wms.ui.group.entity.GroupBatchInfoEntity;
import com.cloud.wms.ui.group.entity.CollectPlaceEntity;
import com.cloud.wms.ui.main.entity.RemoteEntity;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.ui.main.entity.UserEntity;
import com.cloud.wms.ui.sort.entity.DetachBoxBean;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;


/**
 * @Author:Chen
 * @Date: 2021-01-14 15:51
 * @Description: 团购集货
 */
public class GroupCollectPresenter extends BaseRxPresenter<GroupCollectContract.View> implements GroupCollectContract.Presenter {
    public static final int BATCH_LIST = 0x100;
    public static final int COLLECTION_PLACE = 0x101;
    public static final int SUBMIT_COLLECT = 0x102;
    public static final int CHECK_COLLECT_SUCCESS = 0x103;
    public static final int TASK = 0x108;

    @Inject
    public GroupCollectPresenter() {

    }

    /**
     * 集货加载波次列表信息
     *
     * @param batchCode
     */
    @Override
    public void loadBatchList(String batchCode, int page) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        params.put("BatchTypeID", 5);//1.散单分拣，2.单sku分拣，3.笼车分拣，4.团购分拣  5、团购集货 6、团购领用 7、团购抽检
        if (!TextUtils.isEmpty(batchCode)) {
            params.put("BatchCode", batchCode);
        }
        params.put("Sorting", "createDate");
        params.put("SkipCount", PageHelper.skipCount(page));
        params.put("MaxResultCount", PageHelper.PAGE_SIZE);
        FineExApplication
                .component()
                .http()
                .groupBatchList(params)
                .map(new ResponseWrapper<>())
                .map(Page::getItems)
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ArrayList<GroupBatchInfoEntity>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ArrayList<GroupBatchInfoEntity> info) {
                        if (page == 0) {
                            mView.onSuccess(MessageCreator.createMessage(info, PageHelper.LIST_NEW_DATA));
                        } else {
                            mView.onSuccess(MessageCreator.createMessage(info, PageHelper.LIST_NEXT_DATA));
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    @Override
    public void receiveTask(long billId, String taskCode) {
        FineExApplication
                .component()
                .http()
                .orderTaskList(billId + "")
                .map(new ResponseWrapper<>())
                .map(RemoteEntity::getItems)
                .flatMap((Function<ArrayList<TaskEntity>, ObservableSource<TaskEntity>>) Observable::fromIterable)
                .filter(taskEntity -> taskEntity.getTaskCode().equalsIgnoreCase(taskCode))
                .toList()
                .toObservable()
                .flatMap((Function<List<TaskEntity>, ObservableSource<TaskEntity>>) taskEntities -> {
                    if (taskEntities == null || taskEntities.isEmpty()) {
                        return Observable.error(new ApiException("暂无可领用任务"));
                    }
                    TaskEntity taskEntity = taskEntities.get(0);
                    Params params = new Params();
                    params.put("TaskID", taskEntity.getTaskID());
                    UserEntity userInfo = FineExApplication.component().loginCache().getUserInfo();
                    params.put("JobStationID", userInfo.getJobStationID());
                    params.put("ProductCategory", userInfo.getProductCategory());
                    params.put("ExecutorID", userInfo.getUserID());
                    return TaskHelper.receiveTask(params, taskEntity);
                })
                .flatMap((Function<TaskEntity, ObservableSource<TaskEntity>>) taskEntity -> {
                    Params params = new Params();
                    params.put("workId", taskEntity.getWorkID());
                    UserEntity userInfo = FineExApplication.component().loginCache().getUserInfo();
                    params.put("executerId", userInfo.getUserID());
                    return TaskHelper.executeTask(params)
                            .map(aVoid -> taskEntity);
                })
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<TaskEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(TaskEntity info) {
                        mView.onSuccess(MessageCreator.createMessage(info, TASK));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 获取推荐集货地信息
     *
     * @param batchID
     */
    @Override
    public void getCollectionPlaceMsg(String batchID) {
        Params params = Params.newInstance(Params.Type.WAREHOUSE);
        params.put("BatchID", batchID);
        FineExApplication
                .component()
                .http()
                .groupCollectPlace(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<CollectPlaceEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(CollectPlaceEntity collectPlaceEntity) {
                        mView.onSuccess(MessageCreator.createMessage(collectPlaceEntity, COLLECTION_PLACE));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 检测集货地是否可用
     *
     * @param collectCode
     */
    @Override
    public void checkCollect(String collectCode) {
        Params params = Params.newInstance(Params.Type.WAREHOUSE);
        params.put("BoxCode", collectCode);
        params.put("ContainerType", 11);//箱唛 = 1,集货地=11 其它默认0
        FineExApplication
                .component()
                .http()
                .checkBox(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<DetachBoxBean>(mView.provideContext()) {
                    @Override
                    public void onSuccess(DetachBoxBean detachBoxBean) {
                        mView.onSuccess(MessageCreator.createMessage(detachBoxBean, CHECK_COLLECT_SUCCESS));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 确认绑定集货地
     *
     * @param collectID
     */
    @Override
    public void submitCollect(TaskEntity taskEntity, String collectID) {
        UserEntity userEntity = FineExApplication.component().loginCache().getUserInfo();
        Params params = Params.newInstance(Params.Type.WAREHOUSE);
        List<String> list = new ArrayList<>();
        list.add(String.valueOf(taskEntity.getMainBillID()));
        params.put("lstOrderID", list);
        params.put("containerID", collectID);
        params.put("userID", FineExApplication.component().loginCache().getUserInfo().getUserID());
        if (taskEntity != null) {
            params.put("workID", taskEntity.getWorkID());
            params.put("beginTime", taskEntity.getBeginTime());
            params.put("completeTime", TimeUtils.getCurrentDateAndTime());
            params.put("productCategory", userEntity.getProductCategory());
            params.put("jobStationID", userEntity.getJobStationID());
            params.put("appKey", taskEntity.getAppKey());
        }
        FineExApplication
                .component()
                .http()
                .confirmTaskBindCollect(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<Object>(mView.provideContext()) {
                    @Override
                    public void onSuccess(Object object) {
                        mView.onSuccess(MessageCreator.createMessage(object, SUBMIT_COLLECT));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }
}
